#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	widget(new QWidget(this)),
	toolBar(new ToolBar(widget)),
	bookmarkBar(new BookmarkBar(widget)),
	tabBar(new TabBar(widget)),
	view(new WebView(widget)),
	layout(new QVBoxLayout(widget))
{
	addToolBar(Qt::TopToolBarArea, toolBar->bar());
	addToolBar(bookmarkBar->bar());
	layout->setSpacing(0);
	layout->setObjectName(QString::fromUtf8("layout"));
	layout->setContentsMargins(0, 0, 0, 0);
	tabBar->setMaximumHeight(30);
	layout->addWidget(tabBar);
	layout->addWidget(view);
	widget->setLayout(layout);
	setCentralWidget(widget);
	connect(bookmarkBar, SIGNAL(bookmarkOpened(BookmarkItem*,Qt::MouseButton)), this, SLOT(openBookmark(BookmarkItem*,Qt::MouseButton)));
	connect(tabBar, SIGNAL(selectedTabChanged(int)), this, SLOT(emit_needTab(int)));
	connect(tabBar, SIGNAL(tabRemoved(int)), this, SLOT(emit_needRemoveTab(int)));
	connect(tabBar, SIGNAL(tabCreated(int)), this, SLOT(emit_needCreateTab(int)));
	connect(toolBar, SIGNAL(urlChanged(QString)), this, SLOT(slot_urlChanged(QString)));
	connect(view, SIGNAL(titleChanged(QString,int)), tabBar, SLOT(changeTabTitle(QString,int)));
	connect(view, SIGNAL(iconChanged(QIcon,int)), tabBar, SLOT(changeTabIcon(QIcon,int)));
	connect(view, SIGNAL(urlChanged(QString,int)), toolBar, SLOT(changeUrl(QString,int)));
}

void MainWindow::init()
{
	emit_needCreateTab(0);
	show();
}
void MainWindow::openBookmark(BookmarkItem *bookmark, Qt::MouseButton button)
{
	if(button == Qt::LeftButton)
		openUrl(bookmark);
//	else if(button == Qt::MidButton)
//		emit needCreateTab(bookmark);
	bookmark->deleteLater();
}
void MainWindow::slot_urlChanged(QString url)
{
	view->loadUrl(url);
}

void MainWindow::showSelectedTab(TabItem *tab)
{
	toolBar->changeUrl(tab->url());
	view->showPage(tab);
}
void MainWindow::emit_needTab(int index)
{
	emit needTab(index);
}
void MainWindow::showBookmarks(QVector<BookmarkItem *> *bookmarks)
{
	bookmarkBar->showBookmarks(bookmarks);
}
void MainWindow::createTab(TabItem *tab)
{
	tabBar->newTab(tab);
}
void MainWindow::emit_needRemoveTab(int index)
{
	emit needRemoveTab(index);
}
void MainWindow::emit_needCreateTab(int index)
{
	emit needCreateTab(new TabItem("", "New Tab", QIcon::fromTheme("applications-internet"), index));
}

void MainWindow::openUrl(BookmarkItem *bookmark)
{
	tabBar->changeCurrentTab(bookmark);
	view->loadUrl(bookmark->url());
	emit needSaveTab(tabBar->currentTabIndex(), bookmark);
}
